import {_decorator, AudioSource, Component, instantiate, Prefab, resources, director} from 'cc';
import {Constant} from '../../config/Constant';

const {ccclass} = _decorator;


/**
 * 音效管理器
 */
@ccclass('AudioManager')
export class AudioManager extends Component {

    static _instance: AudioManager;
    static get instance(): AudioManager {
        if (this._instance == null) {
            this._instance = new AudioManager();
        }
        return this._instance;
    }

    private bgm: AudioSource | null = null;

    private sfx: Map<string, AudioSource> = new Map()

    onLoad() {
        AudioManager._instance = this;
        // Setting.instance.on(Constant.EVENT_NAME.onBgmVolumeChanged, this.onBgmVolumeChanged, this)
    }

    onDestroy() {
        AudioManager._instance = null;
        // Setting.instance.off(Constant.EVENT_NAME.onBgmVolumeChanged, this.onBgmVolumeChanged, this)
    }

    init() {
        //加载预制体并存储
        let audioNode =director.getScene().getChildByPath(Constant.STATIC_NODE_PATH.Audio)
        let sfx=this.sfx
        resources.loadDir(Constant.DYNAMIC_RESOURCE.Audio.AllPath, Prefab, function (err, assets) {
            assets.forEach((prefab) => {
                let node = instantiate(prefab);
                audioNode.addChild(node);
                const as = node.getComponent(AudioSource);
                sfx.set(prefab.name, as);
            });
        });
    }

    playBgm() {
        if (!this.bgm) {
            return;
        }
        if (this.bgm) {
            this.bgm.stop()
        }
        let node = this.bgm.node;
        node.active = true;
        let as = node.getComponent(AudioSource);
        // as.volume = Setting.instance.bgmVolume;
        this.bgm = as;
    }

    playSfx(path: string) {
        if (!this.sfx.has(path)) {
            return;
        }
        let as = this.sfx.get(path);
        as.play();
    }

    onBgmVolumeChanged() {
        if (this.bgm) {
            // this.bgm.volume = Setting.instance.bgmVolume;
        }
    }
}

